<?php

namespace globalunit\utils;

use QYS\Log\Log;

class WeChatTools
{

    /**
     * 通过 code 获取 AccessToken 和 openid
     * @param $code
     * @param $type
     * @return array
     */
    public static function getAccessToken($appid, $secret)
    {
        $result = CoroutineCurl::request('api.weixin.qq.com', "/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}", 443, true);
        return $result['result'];
    }

    public static function getJsApiTicket($accessToken)
    {
        // $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
        // 微信返回的信息
        $result = CoroutineCurl::request('api.weixin.qq.com', "/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi", 443, true);
        Log::var_dump($result);
        $resData['ticket'] = $result['result']['ticket'];
        $resData['expiresIn'] = $result['result'][ 'expires_in'];
        $resData['time'] = date("Y-m-d H:i", time());
        $resData['errcode'] = $result['result'][ 'errcode'];
        return $resData;
    }

    // 创建随机字符串
    public static function createNoncestr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}
